const storagePath = './temp/bilibili';
import fetch from 'node-fetch';
import fs from 'fs';
import path from 'path';
import common from '../../lib/common/common.js';


export class ExamplePlugin extends plugin {
  constructor() {
    super({
      name: '查bfangled',
      dsc: 'zy-yyds',
      event: 'message',
      priority: -Infinity,
      rule: [
        {
          reg: '^(b站|哔站|逼站|币站|B站)?(开启|关闭)(b站|哔站|逼站|币站|B站)?直播间(自动)?弹幕$',
          fnc: 'toggleAutoDanmaku'
        }
      ]
    });
    this.task = {
      cron: '0 3/15 * * * ?',  
      name: 'b站自动发弹幕',
      fnc: () => this.cf()
  };
  }

  async cf() {
    try {
      const autoDanmakuUsers = this.getAutoDanmakuUsers();
      if (autoDanmakuUsers.length === 0) {
        logger.warn("没有用户开启了自动弹幕");
        return;
      }

      for (const userId of autoDanmakuUsers) {

        await this.sendDanmakuForUser(userId);
        await common.sleep(5000)
      }
    } catch (error) {
      logger.error('Error in cf:', error);
    }
  }

  async toggleAutoDanmaku(e) {
    const action = e.msg.includes('开启') ? '开启' :
                   e.msg.includes('关闭') ? '关闭' : '';
  if (!action) {
      e.reply('指令格式不对，请使用 "开启直播间自动弹幕" 或 "关闭直播间自动弹幕" 格式', true);
      return;
    }
    
    const cookieFile = path.join(storagePath, 'user_cookies.json');
    let cookies = {};
    try {
      cookies = JSON.parse(fs.readFileSync(cookieFile, 'utf8'));
    } catch (err) {
      logger.error("无法读取cookie文件:", err);
      e.reply("未能绑定cookie，请发送b站扫码登录进行绑定", true);
      return;
    }

    const userCookies = cookies[e.user_id];
    if (!userCookies || !userCookies.SESSDATA) {
      e.reply("未能绑定cookie，请发送b站扫码登录进行绑定", true);
      return;
    }

    const autoDanmakuFilePath = path.join(storagePath, 'auto_danmaku_users.json');

    let autoDanmakuUsers = {};
    try {
      autoDanmakuUsers = JSON.parse(fs.readFileSync(autoDanmakuFilePath, 'utf8'));
    } catch (err) {
      // 如果文件不存在或者为空，则初始化为空对象
      if (err.code !== 'ENOENT') {
        logger.error("无法读取自动弹幕用户文件:", err);
        e.reply("系统错误", true);
        return;
      }
    }

    if (action === '开启') {
      autoDanmakuUsers[e.user_id] = true;
      e.reply("直播间自动弹幕已开启", true);
    } else if (action === '关闭') {
      delete autoDanmakuUsers[e.user_id];
      e.reply("直播间自动弹幕已关闭", true);
    }

    // 写入自动弹幕用户设置
    try {
      fs.writeFileSync(autoDanmakuFilePath, JSON.stringify(autoDanmakuUsers, null, 2), 'utf8');
    } catch (err) {
      logger.error("无法写入自动弹幕用户文件:", err);
      e.reply("系统错误", true);
    }
  }

  getAutoDanmakuUsers() {
    const autoDanmakuFilePath = path.join(storagePath, 'auto_danmaku_users.json');
    try {
      const autoDanmakuUsers = JSON.parse(fs.readFileSync(autoDanmakuFilePath, 'utf8'));
      return Object.keys(autoDanmakuUsers).filter(userId => autoDanmakuUsers[userId]);
    } catch (err) {
      if (err.code !== 'ENOENT') {
        logger.error("无法读取自动弹幕用户文件:", err);
      }
      return [];
    }
  }

  async sendDanmakuForUser(userId) {
    try {
      const liveRooms = await this.getLiveRooms(userId);
      if (liveRooms.length === 0) {
        logger.mark(`User ${userId}: 当前没有正在直播的直播间或者直播间已经4小时内发送了弹幕`);
        return;
      }

      for (const roomid of liveRooms) {
        await common.sleep(5000); 
        const msg = await this.getDanmakuMessage(); 
        await this.sendDanmaku(roomid, msg, userId);
      }
    } catch (error) {
      logger.error(`Error sending danmaku for user ${userId}:`, error);
    }
  }

async  getLiveRooms(userId, page = 1) {
    // 获取用户的 cookies
    const cookieFile = path.join(storagePath, 'user_cookies.json');
    let cookies = {};
    try {
        cookies = JSON.parse(fs.readFileSync(cookieFile, 'utf8'));
    } catch (err) {
        logger.error("无法读取cookie文件:", err);
        throw new Error("未能绑定cookie，请发送b站扫码登录进行绑定");
    }

    const userCookies = cookies[userId];
    if (!userCookies || !userCookies.SESSDATA) {
        logger.warn(`User ${userId} does not have valid cookies.`);
        throw new Error("未能绑定cookie，请发送b站扫码登录进行绑定");
    }

    // 构建请求头和参数
    const { access_token, SESSDATA: sessdata, csrf, DedeUserID, DedeUserID__ckMd5, sid } = userCookies;
    const params = new URLSearchParams({
        page,
        page_size: 10,
        ignoreRecord: '1',
        hit_ab: 'true'
    });
    const url = `https://api.live.bilibili.com/xlive/web-ucenter/user/following?${params}`;
    const headers = {
        referer: 'https://www.bilibili.com/',
        Cookie: `access_token=${access_token}; SESSDATA=${sessdata}; csrf=${csrf}; DedeUserID=${DedeUserID}; DedeUserID__ckMd5=${DedeUserID__ckMd5}; sid=${sid}`,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
        'Content-Type': 'application/x-www-form-urlencoded'
    };

      // 开始递归获取直播间的函数
      async function fetchPages(page, accumulatedLiveRooms = []) {
        try {
          const response = await fetch(url, { headers });
          const data = await response.json();
  
          if (data.code !== 0) {
            throw new Error(`Failed to fetch live rooms: ${data.message || data.msg}`);
          }
  
          // 收集当前页所有正在直播的房间及其主播昵称
          const liveRoomsPage = data.data.list.filter(item => item.live_status === 1).map(item => ({ roomid: item.roomid, uname: item.uname }));
  
          // 累积所有直播间的房间号和主播昵称
          const allLiveRooms = [...accumulatedLiveRooms, ...liveRoomsPage];
  
          // 检查是否需要请求下一页...
          if (data.data.page && data.data.page.num < data.data.page.count) {
            await common.sleep(1500); 
            return fetchPages(page + 1, allLiveRooms);
          }
  
          // 返回所有收集到的直播间列表及主播昵称
          return allLiveRooms;
        } catch (error) {
          logger.error('Error fetching live rooms:', error);
          throw error;
        }
      }

       // 执行获取直播间信息并进行 Redis 过滤...
       try {
        const allLiveRooms = await fetchPages(page);
        // 在所有直播间收集完毕后，使用 Redis 进行二次过滤...
        const filteredLiveRooms = [];
        for (const { roomid, uname } of allLiveRooms) {
          const key = `autolivesend:${userId}:${roomid}`;
          if (!(await redis.get(key))) {
            filteredLiveRooms.push({ roomid, uname });
          }
        }
  
        // 返回经过 Redis 过滤后的直播间列表及主播昵称
        return filteredLiveRooms;
      } catch (error) {
        logger.error('Error processing live rooms:', error);
        throw error;
      }
    }
  
  async  getDanmakuMessage() {
    try {
        const response = await fetch('https://yuanshen.zy1314.icu/text?wb=yy&type=text');
        const data = await response.text();
        return data.length > 20 ? data.slice(0, 20) : data;
    } catch (error) {
        logger.error('Fetch error:', error);
        return '冒泡';
    }
}

async sendDanmaku(roomInfo, msg, userId) {
    const cookieFile = path.join(storagePath, 'user_cookies.json');
    let cookies = {};
    try {
      cookies = JSON.parse(fs.readFileSync(cookieFile, 'utf8'));
    } catch (err) {
      logger.error("无法读取cookie文件:", err);
      return;
    }

    const userCookies = cookies[userId];
    if (!userCookies || !userCookies.SESSDATA) {
      logger.warn(`User ${userId} does not have valid cookies.`);
      return;
    }

    const { access_token, SESSDATA: sessdata, csrf, DedeUserID, DedeUserID__ckMd5, sid } = userCookies;

    const url = 'https://api.live.bilibili.com/msg/send';
    const headers = {
      referer: 'https://www.bilibili.com/',
      Cookie: `access_token=${access_token}; SESSDATA=${sessdata}; csrf=${csrf}; DedeUserID=${DedeUserID}; DedeUserID__ckMd5=${DedeUserID__ckMd5}; sid=${sid}`,
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
      'Content-Type': 'application/x-www-form-urlencoded'
    };
    const postData = new URLSearchParams({
      color: 16777215,
      fontsize: 25,
      mode: 1,
      msg,
      rnd: Math.floor(Date.now() / 1000),
      roomid: roomInfo.roomid,
      bubble: 0,
      csrf_token: csrf,
      csrf
    });

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers,
        body: postData
      });

      const result = await response.json();
      if (result.code === 0) {
        if(await redis.get(`${userId}`)){
          const groupid = await redis.get(`${userId}`)
          await Bot.pickGroup(groupid).sendMsg(
            `[b站自动发弹幕推送]【用户${userId}】向主播【${roomInfo.uname}】的直播间【${roomInfo.roomid}】发送弹幕成功: \n${msg}`
          )
        }
        logger.mark(`${userId} 向 ${roomInfo.roomid} 直播间发送弹幕成功: ${msg}`);
        let key = `autolivesend:${userId}:${roomInfo.roomid}`
        redis.set(key, "1", { EX: 14400 })  // 4小时
      } else {
        if(await redis.get(`${userId}`)){
          const groupid = await redis.get(`${userId}`)
          await Bot.pickGroup(groupid).sendMsg(
            `[b站自动发弹幕推送]【用户${userId}】向主播【${roomInfo.uname}】的直播间【${roomInfo.roomid}】发送弹幕【${msg}】失败: \n${result.message || result.msg}`
          )
        }
        logger.error(`发送失败 ${roomInfo.roomid}: ${result.message || result.msg}`);
      }
    } catch (error) {
      logger.error('Error sending danmaku:', error);
    }
  }
}